package com.winning.pmph.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.winning.pmph.entity.*;
import com.winning.pmph.enumeration.KnowledgeSystem;
import com.winning.pmph.mapper.PlatformKnowledgeLibMapper;
import com.winning.pmph.mapper.PlatformMapper;
import com.winning.pmph.mapper.TermBookMetadataMapper;
import com.winning.pmph.utils.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Transactional
public class PlatformService extends ServiceImpl<PlatformMapper, Platform> {

    @Resource
    private TagService tagService;
    @Resource
    private CalculatorService calculatorService;
    @Resource
    private KnowledgeLibService knowledgeLibService;
    @Resource
    private KnowledgeLibFieldService knowledgeLibFieldService;
    @Resource
    private ReleasedKnowledgeService releasedKnowledgeService;
    @Resource
    private JournalService journalService;
    @Resource
    private KnowledgeSyncStatusService knowledgeSyncStatusService;
    @Resource
    private PlatformKnowledgeLibMapper platformKnowledgeLibMapper;
    @Resource
    private RocketMQProducerService rocketMQProducerService;
    @Resource
    private BookService bookService;
    @Resource
    private TermService termService;
    @Resource
    private TermBookMetadataMapper termBookMetadataMapper;
    @Resource
    private FlowChartService flowChartService;
    @Resource
    private SpecialtyKnowledgeLibService specialtyKnowledgeLibService;

    private void sendTagAndKnowledgeLibList(List<PlatformKnowledgeLib> platformKnowledgeLibs, List<String> finalWaitForSyncTopTagList, String username) {
        String platformId = platformKnowledgeLibs.get(0).getPlatformId();
        // 先同步tag;
        for (String topTagId : finalWaitForSyncTopTagList) {
            Tag topTag = tagService.getById(topTagId);
            rocketMQProducerService.sendTagToTopic(platformId, topTag);
            List<Tag> allTags = tagService.selectSubTagListByTopTagId(topTagId);
            allTags.forEach(tag -> rocketMQProducerService.sendTagToTopic(platformId, tag));
        }
        // 同步knowledgeLib时,添加对应的专科知识库信息
        Map<Object, Set<SpecialtyKnowledgeLib>> specialtyMap = Maps.newHashMap();
        specialtyKnowledgeLibService.lambdaQuery().list().forEach(item -> {
            item.getKnowledgeLibIdList().forEach(libIdItem -> {
                Set<SpecialtyKnowledgeLib> specialtyKnowledgeLibSet = specialtyMap.getOrDefault(libIdItem, Sets.newHashSet());
                specialtyKnowledgeLibSet.add(item);
                specialtyMap.put(libIdItem, specialtyKnowledgeLibSet);
            });
        });
        // 再同步knowledgeLib;
        for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
            // 同步knowledgeLib;
            KnowledgeLib knowledgeLib = knowledgeLibService.getById(platformKnowledgeLib.getKnowledgeLibId());
            // 如果是新增, 则需要同步knowledgeLib;
            knowledgeLib.setSpecialtySet(specialtyMap.getOrDefault(knowledgeLib.getId(), Sets.newHashSet()));
            List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldService.lambdaQuery().eq(KnowledgeLibField::getKnowledgeLibId, knowledgeLib.getId()).orderByAsc(KnowledgeLibField::getIndex).list();
            knowledgeLib.setFieldList(knowledgeLibFields);
            rocketMQProducerService.sendKnowledgeLib(platformId, knowledgeLib);
            List<ReleasedKnowledge> releasedKnowledges = releasedKnowledgeService.getBaseMapper().selectBeansByWherePart(
                    " knowledge_lib_id = '" + platformKnowledgeLib.getKnowledgeLibId() + "'" +
                            " and deleted = 0");
            // 再同步知识, 先删除同步记录;
            knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                    .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                    .eq(KnowledgeSyncStatus::getPlatformId, platformId));
            if (platformKnowledgeLib.isAutosyncFlag()) {
                for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                    // 同步知识;
                    releasedKnowledge.setKnowledgeLibName(knowledgeLib.getName());
                    rocketMQProducerService.sendKnowledge(platformId, releasedKnowledge, username);
                }
            }
            // 未开启自动同步, 插入status表, 待同步状态
            else {
                List<KnowledgeSyncStatus> knowledgeSyncStatusList = Lists.newArrayList();
                for (ReleasedKnowledge releasedKnowledge : releasedKnowledges) {
                    KnowledgeSyncStatus knowledgeSyncStatus = new KnowledgeSyncStatus();
                    knowledgeSyncStatus.setKind(KnowledgeSyncStatus.FAILED_KIND_WAITING);
                    knowledgeSyncStatus.setKnowledgeId(releasedKnowledge.getId());
                    knowledgeSyncStatus.setKnowledgeLibId(knowledgeLib.getId());
                    knowledgeSyncStatus.setVersion(releasedKnowledge.getVersion());
                    knowledgeSyncStatus.setOperatedTime(LocalDateTimeUtil.getNowAsString());
                    knowledgeSyncStatus.setPlatformId(platformId);
                    knowledgeSyncStatusList.add(knowledgeSyncStatus);
                }
                knowledgeSyncStatusService.saveBatch(knowledgeSyncStatusList);
            }
        }
    }


    public void savePlatform(Platform platform) {
        saveOrUpdate(platform);
        // 如果平台未启用, 则关闭所有自动同步知识库, 并删除所有同步失败数据;
        if (!platform.getStatus()) {
            platformKnowledgeLibMapper.executeUpdate("update platform_knowledge_lib" +
                    " set autosync_flag = 0 where platform_id = '" + platform.getId() + "'");
            knowledgeSyncStatusService.getBaseMapper().executeDelete("delete from knowledge_sync_status " +
                    " where platform_id = '" + platform.getId() + "'");
        }
    }


    public void savePlatformKnowledgeLibs(List<PlatformKnowledgeLib> platformKnowledgeLibs, String userName) {
        String platformId = platformKnowledgeLibs.get(0).getPlatformId();
        boolean insertFlag = StringUtils.isEmpty(platformKnowledgeLibs.get(0).getId());
        // 新增绑定关系
        if (insertFlag) {
            // 知识库类型,同步知识库结构,关联的分类标签和已发布的知识
            if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.KNOWLEDGE.value)) {
                if (StringUtils.equals(platformId, "rwtgdj")) {
                    ExecutorServiceFactory.getInstance().submit(() -> sendKnowledgeLibAndField(platformKnowledgeLibs, platformId));
                } else {
                    // 知识库id集合;
                    List<String> knowledgeLibIds = platformKnowledgeLibs.stream().map(PlatformKnowledgeLib::getKnowledgeLibId)
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(knowledgeLibIds)) {
                        // 准备待同步tag;
                        // 当前knowledgeLibIds 关联 tag;
                        List<KnowledgeLibField> knowledgeLibFieldList = knowledgeLibFieldService.getBaseMapper().executeMultiSelect("select DISTINCT KIND_VALUE from knowledge_lib_field where knowledge_lib_id in " +
                                knowledgeLibIds.stream().collect(Collectors.joining("','", "('", "')")) +
                                "and KIND_VALUE is not null and KIND_VALUE != '' ");
                        List<String> topTagIds = Lists.newArrayList();
                        if (CollectionUtils.isNotEmpty(knowledgeLibFieldList)) {
                            topTagIds = knowledgeLibFieldList.stream().map(KnowledgeLibField::getKindValue).collect(Collectors.toList());
                        }
                        // 当前平台已关联的知识库ID;
                        List<PlatformKnowledgeLib> platformKnowledgeLibList = platformKnowledgeLibMapper.executeMultiSelect(" select DISTINCT knowledge_lib_id from platform_knowledge_lib" +
                                " where platform_id = '" + platformId + "'");
                        List<String> dbKnowledgeLibIds = Lists.newArrayList();
                        if (CollectionUtils.isNotEmpty(platformKnowledgeLibList)) {
                            dbKnowledgeLibIds = platformKnowledgeLibList.stream().map(PlatformKnowledgeLib::getKnowledgeLibId).collect(Collectors.toList());
                        }
                        // 当前平台已同步的tagIds;
                        List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldService.getBaseMapper().executeMultiSelect("select DISTINCT KIND_VALUE from knowledge_lib_field where knowledge_lib_id in " +
                                dbKnowledgeLibIds.stream().collect(Collectors.joining("','", "('", "')")) +
                                "and KIND_VALUE is not null and KIND_VALUE != '' ");
                        List<String> dbAutoSyncTopTagIds = Lists.newArrayList();
                        if (CollectionUtils.isNotEmpty(knowledgeLibFields)) {
                            dbAutoSyncTopTagIds = knowledgeLibFields.stream().map(KnowledgeLibField::getKindValue).collect(Collectors.toList());
                        }
                        List<String> finalDbAutoSyncTopTagIds = dbAutoSyncTopTagIds;
                        List<String> waitAutoSyncTopTagIds = topTagIds.stream().filter(id -> !finalDbAutoSyncTopTagIds.contains(id))
                                .filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                        // 同步mq任务;
                        List<String> finalWaitForSyncTopTagList = waitAutoSyncTopTagIds;
                        String username = PMPHAppUtil.getCurrentUserEnName();
                        ExecutorServiceFactory.getInstance().submit(() -> sendTagAndKnowledgeLibList(platformKnowledgeLibs, finalWaitForSyncTopTagList, username));
                    }
                }
            } else if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.CALCULATOR.value)) {
                // 新增绑定医学计算器
                // 新起线程操作,避免数据量大,导致页面卡死
                ExecutorServiceFactory.getInstance().submit(() -> {
                    for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
                        // 先删除knowledge_sync_status表,保证知识ID唯一,该表用来记录该条知识的同步状态
                        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId));
                        List<ReleasedMedicalCalculator> releasedMedicalCalculators = calculatorService.getReleasedMedicalCalculator();
                        if (releasedMedicalCalculators.size() == 0) {
                            continue;
                        }
                        if (platformKnowledgeLib.isAutosyncFlag()) {
                            String calculatorIds = releasedMedicalCalculators.stream().map(ReleasedMedicalCalculator::getId).collect(Collectors.joining(","));
                            calculatorService.syncCalculator(platformId, calculatorIds);
                        } else {
                            // 未开启自动同步, 插入status表, 待同步状态
                            List<KnowledgeSyncStatus> knowledgeSyncStatusList = Lists.newArrayList();
                            for (ReleasedMedicalCalculator releasedMedicalCalculator : releasedMedicalCalculators) {
                                KnowledgeSyncStatus knowledgeSyncStatus = new KnowledgeSyncStatus();
                                knowledgeSyncStatus.setKind(KnowledgeSyncStatus.FAILED_KIND_WAITING);
                                knowledgeSyncStatus.setKnowledgeId(releasedMedicalCalculator.getId());
                                knowledgeSyncStatus.setKnowledgeLibId(platformKnowledgeLib.getKnowledgeLibId());
                                knowledgeSyncStatus.setVersion(releasedMedicalCalculator.getVersion());
                                knowledgeSyncStatus.setOperatedTime(LocalDateTimeUtil.getNowAsString());
                                knowledgeSyncStatus.setPlatformId(platformId);
                                knowledgeSyncStatusList.add(knowledgeSyncStatus);
                            }
                            knowledgeSyncStatusService.saveBatch(knowledgeSyncStatusList);
                        }
                    }
                });
            } else if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.JOURNAL.value)) {
                // 新增绑定期刊
                ExecutorServiceFactory.getInstance().submit(() -> {
                    for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
                        // 先删除knowledge_sync_status表,保证知识ID唯一,该表用来记录该条知识的同步状态
                        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId));
                        List<Journal> journalList = journalService.getBaseMapper().selectBeansByWherePart(" `type` = 1 and issn = '" + platformKnowledgeLib.getKnowledgeLibId() + "'");
                        if (journalList.size() == 0) {
                            continue;
                        }
                        if (platformKnowledgeLib.isAutosyncFlag()) {
                            // 开启自动同步
                            String journalIds = journalList.stream().map(Journal::getId).collect(Collectors.joining(","));
                            Journal journal = new Journal();
                            journal.setId(journalIds);
                            journal.setSelectedPlatform(platformKnowledgeLib.getPlatformId());
                            journalService.syncToPlatform(journal, userName, Const.SYNC_OPERATION_ADD);
                        } else {
                            // 未开启自动同步, 插入status表, 待同步状态
                            List<KnowledgeSyncStatus> knowledgeSyncStatusList = Lists.newArrayList();
                            for (Journal journal : journalList) {
                                KnowledgeSyncStatus knowledgeSyncStatus = new KnowledgeSyncStatus();
                                knowledgeSyncStatus.setKind(KnowledgeSyncStatus.FAILED_KIND_WAITING);
                                knowledgeSyncStatus.setKnowledgeId(journal.getId());
                                knowledgeSyncStatus.setKnowledgeLibId(platformKnowledgeLib.getKnowledgeLibId());
                                knowledgeSyncStatus.setOperatedTime(LocalDateTimeUtil.getNowAsString());
                                knowledgeSyncStatus.setPlatformId(platformId);
                                knowledgeSyncStatusList.add(knowledgeSyncStatus);
                            }
                            knowledgeSyncStatusService.saveBatch(knowledgeSyncStatusList);
                        }
                    }
                });
            } else if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.BOOK.value)) {
                // 新增绑定图书
                ExecutorServiceFactory.getInstance().submit(() -> {
                    for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
                        // 先删除knowledge_sync_status表,保证知识ID唯一,该表用来记录该条知识的同步状态
                        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId));
                        List<Book> bookList = bookService.lambdaQuery().eq(Book::getStatus, Book.BOOK_STATUS_PUBLISHED).list();
                        if (bookList.size() == 0) {
                            continue;
                        }
                        if (platformKnowledgeLib.isAutosyncFlag()) {
                            // 开启自动同步
                            String bookIds = bookList.stream().map(Book::getId).collect(Collectors.joining(","));
                            Arrays.asList(bookIds.split(",")).forEach(id -> {
                                bookService.syncBook(id, platformId, userName);
                            });
                        } else {
                            // 未开启自动同步, 插入status表, 待同步状态
                            List<KnowledgeSyncStatus> knowledgeSyncStatusList = Lists.newArrayList();
                            for (Book book : bookList) {
                                KnowledgeSyncStatus knowledgeSyncStatus = new KnowledgeSyncStatus();
                                knowledgeSyncStatus.setKind(KnowledgeSyncStatus.FAILED_KIND_WAITING);
                                knowledgeSyncStatus.setKnowledgeId(book.getId());
                                knowledgeSyncStatus.setKnowledgeLibId(platformKnowledgeLib.getKnowledgeLibId());
                                knowledgeSyncStatus.setOperatedTime(LocalDateTimeUtil.getNowAsString());
                                knowledgeSyncStatus.setPlatformId(platformId);
                                knowledgeSyncStatusList.add(knowledgeSyncStatus);
                            }
                            knowledgeSyncStatusService.saveBatch(knowledgeSyncStatusList);
                        }
                    }
                });
            } else if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.TERM.value)) {
                // 新增绑定术语
                ExecutorServiceFactory.getInstance().submit(() -> {
                    // 先删除knowledge_sync_status表,保证知识ID唯一,该表用来记录该条知识的同步状态
                    knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                            .in(KnowledgeSyncStatus::getKnowledgeLibId,
                                    platformKnowledgeLibs.stream().map(PlatformKnowledgeLib::getKnowledgeLibId).collect(Collectors.toList()))
                            .eq(KnowledgeSyncStatus::getPlatformId, platformId));
                    // 开启自动同步
                    if (platformKnowledgeLibs.get(0).isAutosyncFlag()) {
                        // 新增绑定关系时,推送图书元数据,只推图书级别不为空的数据
                        termBookMetadataMapper.lambdaQuery().isNotNull(TermBookMetadata::getCategory)
                                .notIn(TermBookMetadata::getStatus, 0, 4).list().forEach(termBookMetadata -> {
                            Term term = new Term();
                            term.setTermBookMetadataId(termBookMetadata.getId());
                            term.setSelectedPlatform(platformKnowledgeLibs.get(0).getPlatformId());
                            termService.syncToPlatform(term, userName, Const.SYNC_OPERATION_ADD);
                        });
                    }
                });
            } else if (StringUtils.equals(platformKnowledgeLibs.get(0).getSystemType(), KnowledgeSystem.FLOWCHART.value)) {
                // 新增绑定流程图
                ExecutorServiceFactory.getInstance().submit(() -> {
                    // 先删除knowledge_sync_status表,保证知识ID唯一,该表用来记录该条知识的同步状态
                    knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                            .in(KnowledgeSyncStatus::getKnowledgeLibId,
                                    platformKnowledgeLibs.stream().map(PlatformKnowledgeLib::getKnowledgeLibId).collect(Collectors.toList()))
                            .eq(KnowledgeSyncStatus::getPlatformId, platformId));
                    // 开启自动同步
                    if (platformKnowledgeLibs.get(0).isAutosyncFlag()) {
                        ReleasedFlowChart releasedFlowChart = new ReleasedFlowChart();
                        releasedFlowChart.setSelectedPlatform(platformId);
                        flowChartService.syncToPlatform(releasedFlowChart, userName, Const.SYNC_OPERATION_ADD);
                    }
                });
            }
        } else if (platformKnowledgeLibs.get(0).isAutosyncFlag()) {
            // 修改, 只能修改自动同步开关;
            // 如果改为自动同步, 则开启同步线程, 否则不需要做改动;
            for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
                // 调用一键同步接口;
                String username = PMPHAppUtil.getCurrentUserEnName();
                // 知识
                if (KnowledgeSystem.KNOWLEDGE.value.equals(platformKnowledgeLib.getSystemType())) {
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        knowledgeLibService.syncWaitAndFailedKnowledgeToPlatform(platformKnowledgeLib.getPlatformId(),
                                platformKnowledgeLib.getKnowledgeLibId(), username);
                    });
                } else if (KnowledgeSystem.CALCULATOR.value.equals(platformKnowledgeLib.getSystemType())) {
                    // 医学计算器
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
                        for (KnowledgeSyncStatus knowledgeSyncStatus : knowledgeSyncStatusList) {
                            ReleasedMedicalCalculator releasedMedicalCalculator = calculatorService.getReleasedMedicalCalculatorById(knowledgeSyncStatus.getKnowledgeId());
                            if (Objects.isNull(releasedMedicalCalculator)) {
                                knowledgeSyncStatusService.removeById(knowledgeSyncStatus.getId());
                            } else {
                                calculatorService.syncCalculator(platformId, knowledgeSyncStatus.getKnowledgeId());
                            }
                        }
                    });
                } else if (KnowledgeSystem.JOURNAL.value.equals(platformKnowledgeLib.getSystemType())) {
                    // 期刊,只同步待同步和失败的数据
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
                        for (KnowledgeSyncStatus knowledgeSyncStatus : knowledgeSyncStatusList) {
                            Journal journal = journalService.getBaseMapper().selectById(knowledgeSyncStatus.getKnowledgeId());
                            if (Objects.isNull(journal)) {
                                knowledgeSyncStatusService.removeById(knowledgeSyncStatus.getId());
                            } else {
                                journal.setSelectedPlatform(platformId);
                                journalService.syncToPlatform(journal, userName, Const.SYNC_OPERATION_ADD);
                            }
                        }
                    });
                } else if (KnowledgeSystem.BOOK.value.equals(platformKnowledgeLib.getSystemType())) {
                    // 图书,只同步待同步和失败的数据
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusService.lambdaQuery()
                                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                                .eq(KnowledgeSyncStatus::getKnowledgeLibId, platformKnowledgeLib.getKnowledgeLibId())
                                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS).list();
                        for (KnowledgeSyncStatus knowledgeSyncStatus : knowledgeSyncStatusList) {
                            Book book = bookService.getBaseMapper().selectById(knowledgeSyncStatus.getKnowledgeId());
                            if (Objects.isNull(book)) {
                                knowledgeSyncStatusService.removeById(knowledgeSyncStatus.getId());
                            } else {
                                bookService.syncBook(book.getId(), platformId, userName);
                            }
                        }
                    });
                } else if (KnowledgeSystem.TERM.value.equals(platformKnowledgeLib.getSystemType())) {
                    // 术语,只同步待同步和失败的数据,除去在状态表里同步成功的数据,不在状态表里记录的数据是待同步数据
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        termService.syncWaitAndFailedToPlatform(platformKnowledgeLibs.get(0).getPlatformId(),
                                userName, Const.SYNC_OPERATION_ADD);
                    });
                } else if (KnowledgeSystem.FLOWCHART.value.equals(platformKnowledgeLib.getSystemType())) {
                    // 只同步待同步和失败的数据,除去在状态表里同步成功的数据,不在状态表里记录的数据是待同步数据
                    ExecutorServiceFactory.getInstance().submit(() -> {
                        flowChartService.syncWaitAndFailedToPlatform(platformKnowledgeLibs.get(0).getPlatformId(),
                                userName, Const.SYNC_OPERATION_ADD);
                    });
                }
            }
        }
        platformKnowledgeLibs.forEach(platformKnowledgeLibMapper::saveBean);
    }

    public void deletePlatformKnowledgeLibById(PlatformKnowledgeLib platformKnowledgeLib) {
        // 删除关系;
        platformKnowledgeLibMapper.deleteById(platformKnowledgeLib.getId());

        if (KnowledgeSystem.KNOWLEDGE.value.equals(platformKnowledgeLib.getSystemType())) {
            // 清理knowledge_sync_status---知识;
            String sql = " delete from knowledge_sync_status " +
                    " where platform_id = '" + platformKnowledgeLib.getPlatformId() + "' " +
                    " and knowledge_id in (select id from released_knowledge where knowledge_lib_id = '" + platformKnowledgeLib.getKnowledgeLibId() + "') ";
            knowledgeSyncStatusService.getBaseMapper().executeDelete(sql);
        }
        if (KnowledgeSystem.CALCULATOR.value.equals(platformKnowledgeLib.getSystemType())) {
            // 清理knowledge_sync_status---医学计算器;
            String calcSql = " delete from knowledge_sync_status " +
                    " where platform_id = '" + platformKnowledgeLib.getPlatformId() + "' " +
                    " and knowledge_lib_id = 'calculator_lib_id'";
            knowledgeSyncStatusService.getBaseMapper().executeDelete(calcSql);
        }
        if (KnowledgeSystem.JOURNAL.value.equals(platformKnowledgeLib.getSystemType())) {
            // 清理knowledge_sync_status---期刊;
            String journalSql = " delete from knowledge_sync_status " +
                    " where platform_id = '" + platformKnowledgeLib.getPlatformId() + "' " +
                    " and knowledge_id in (select id from journal where issn = '" + platformKnowledgeLib.getKnowledgeLibId() + "' and type = 1)";
            knowledgeSyncStatusService.getBaseMapper().executeDelete(journalSql);
        }
        if (KnowledgeSystem.BOOK.value.equals(platformKnowledgeLib.getSystemType())) {
            String bookSql = " delete from knowledge_sync_status " +
                    " where platform_id = '" + platformKnowledgeLib.getPlatformId() + "' " +
                    " and knowledge_lib_id = 'book_lib_id'";
            knowledgeSyncStatusService.getBaseMapper().executeDelete(bookSql);
        }
    }


    public void deletePlatformById(String id) {
        // 删除platform表;
        removeById(id);
        // 删除平台知识库关系表;
        platformKnowledgeLibMapper.delete(Wrappers.lambdaQuery(PlatformKnowledgeLib.class).eq(PlatformKnowledgeLib::getPlatformId, id));
        // 删除knowledge_sync_status;
        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class).eq(KnowledgeSyncStatus::getPlatformId, id));
    }

    private void sendKnowledgeLibAndField(List<PlatformKnowledgeLib> platformKnowledgeLibs, String platformId) {
        for (PlatformKnowledgeLib platformKnowledgeLib : platformKnowledgeLibs) {
            // 同步knowledgeLib;
            KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(platformKnowledgeLib.getKnowledgeLibId());
            // 如果是新增, 则需要同步knowledgeLib;
            List<KnowledgeLibField> knowledgeLibFields = knowledgeLibFieldService.getBaseMapper().executeMultiSelect("select * from knowledge_lib_field where knowledge_lib_id = '" + knowledgeLib.getId() + "' order by `index`");
            knowledgeLib.setFieldList(knowledgeLibFields);
            rocketMQProducerService.sendKnowledgeLib(platformId, knowledgeLib);
        }
    }
}

